<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-row>
        <el-form-item label="关联的MCU设备" prop="mcuTenantResourceId">
          <el-select v-model="queryParams.mcuTenantResourceId" placeholder="请选择关联的MCU设备" clearable
                     @keyup.enter.native="handleQuery" style="width:300px">
            <el-option
              v-for="item in mcuTenantResourceListData"
              :key="item.id"
              :label="item.name+'-（'+item.remark+'）'"
              :value="item.id">
              <span style="float: left">{{ item.model }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）-（{{ item.remark }}）</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="queryParams.model" placeholder="请输入型号" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
      </el-row>
      <el-form-item label="名称" prop="name" >
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" style="width:300px"/>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['hardware:sensor-tenant-resource:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['hardware:sensor-tenant-resource:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" >
      <el-table-column  label="关联的MCU设备" align="center" width="280">
        <template slot-scope="scope">
          <span v-for="item in mcuTenantResourceListData"  :key="item.id" v-if="scope.row.mcuTenantResourceId===item.id">
            {{item.model+'（'+item.name+'）（'+item.remark+'）'}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model"  width="180"/>
      <el-table-column label="名称" align="center" prop="name"  width="150"/>
      <el-table-column label="通道号" align="center" prop="mcuChannel"  width="80"/>
      <el-table-column label="属性值" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" width="500">
            <el-descriptions :column="2" size="mini" >
              <el-descriptions-item v-for="it in scope.row.attributeMetadata" :key="it.code" v-if="it.isShow"    :label="it.name">
                <el-tag size="small">{{it.inputValue}}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">查看属性数据</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="预警值" align="center" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p v-for="it in scope.row.warningMetadata" >{{it.name}} : <span style="color: #ffba00;">{{it.conditions}}</span>  <span style="color: #e50839;"> {{ it.value }}</span></p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">查看预警数据</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'info')">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'update')"
                     v-hasPermi="['hardware:sensor-tenant-resource:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['hardware:sensor-tenant-resource:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>


    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" custom-class="sitesFormDialog" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px"  :disabled="formDisabled">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联的MCU" prop="mcuTenantResourceId">
              <el-select v-model="form.mcuTenantResourceId" placeholder="请选择关联的MCU"
                         @change="querySensorTenantTypeListData" style="width:100%">
                <el-option
                  v-for="item in mcuTenantResourceListData"
                  :key="item.id"
                  :label="item.name+'-（'+item.remark+'）'"
                  :value="item.id">
                  <span style="float: left">{{ item.model }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）-（{{
                      item.remark
                    }}）</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="通道号" prop="mcuChannel">
              <el-input-number v-model="form.mcuChannel" size="mini" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联的传感器" prop="model">
              <el-select v-model="form.model" placeholder="请选择关联的传感器" @change="changeSensorType"  style="width:100%">
                <el-option
                  v-for="item in sensorTenantTypeListData"
                  :key="item.model"
                  :label="item.model+'（'+item.name+'）'"
                  :value="item.model">
                  <span style="float: left">{{ item.model }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      <!-- 自定义属性 -->
        <el-row :gutter="20" >
          <div v-for="item in form.attributeMetadata" :key="item.id" >
            <el-col :span="12">
              <el-form-item  v-if="item.isShow"  :label="item.name"  :prop="item.code">
                <el-input v-if="item.htmlType =='input'" v-model="item.inputValue" :placeholder="item.placeholder"/>

                <el-select v-if="item.htmlType =='select'" v-model="item.inputValue" :placeholder="item.placeholder"  style="width:100%">
                  <el-option v-for="it in item.dynamicTags" :key="it" :label="it" :value="it"></el-option>
                </el-select>

                <el-switch v-if="item.htmlType =='switch'" v-model="item.inputValue" active-color="#13ce66" inactive-color="#ff4949"></el-switch>

                <el-date-picker v-if="item.htmlType =='datetime'" v-model="item.inputValue"  type="datetime" :placeholder="item.placeholder"></el-date-picker>

                <el-input-number  v-if="item.htmlType =='inputNumber'" v-model="item.inputValue" size="mini" controls-position="right" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
          </div>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="13">
            <el-form-item label="预警数据" prop="warningMetadata">
              <el-button type="warning" plain round @click="addWarningMetadataItem">新增预警</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0" v-for="item in form.warningMetadata" :key="item.id">
          <el-col :span="8">
            <el-form-item label="预警属性">
              <el-select v-model="item.code">
                <el-option
                  v-for="it in form.valueMetadata"
                  :key="it.code"
                  :label="it.name"
                  :value="it.code">
                  <span style="float: left">{{ it.code }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">（{{it.name}}）</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预警条件">
              <el-select v-model="item.conditions" placeholder="请选择预警属条件类型">
                <el-option label="大于" value="大于"></el-option>
                <el-option label="小于" value="小于"></el-option>
                <el-option label="等于" value="等于"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="预警值">
              <el-input-number v-model="item.value" :precision="6" :step="1"  size="mini" controls-position="right"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="">
              <el-button type="danger" icon="el-icon-delete" circle @click.prevent="removeWarningMetadataItem(item)"></el-button>
            </el-form-item>
          </el-col>
        </el-row>


<!--
        <el-row>
          <el-table border ref="dragTable" :data="form.warningMetadata" :max-height="tableHeight">
            <el-table-column label="预警对应的属性" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-select v-model="scope.row.code">
                  <el-option
                    v-for="item in form.valueMetadata"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                    <span style="float: left">{{ item.code }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">（{{item.name}}）</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="预警属性条件" min-width="10%">
              <template slot-scope="scope">
                  <el-select v-model="scope.row.conditions" placeholder="请选择预警属条件类型">
                    <el-option label="大于" value="大于"></el-option>
                    <el-option label="小于" value="小于"></el-option>
                    <el-option label="等于" value="等于"></el-option>
                  </el-select>
              </template>
            </el-table-column>

            <el-table-column label="预警值" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.value" :precision="6" :step="1"  size="mini" controls-position="right"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="5%">
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" circle @click.prevent="removeWarningMetadataItem(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
-->

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createSensorTenantResource,
  deleteSensorTenantResource,
  exportSensorTenantResourceExcel,
  getSensorTenantResource,
  getSensorTenantResourcePage,
  updateSensorTenantResource
} from "@/api/hardware/sensorTenantResource";
import {getMcuTenantResourceList} from "@/api/hardware/mcuTenantResource";
import {getSensorTenantTypeInfoList} from "@/api/hardware/sensorTenantType";
import {getTenantId} from '@/utils/auth'


export default {
  name: "SensorTenantResource",
  components: {},
  data() {
    return {
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传感器租户配置列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        tenantId: getTenantId(),
        pageNo: 1,
        pageSize: 10,
        mcuTenantResourceId: null,
        model: null,
        name: null,
        remark: null,
      },
      // 表单参数
      form: {
        attributeMetadata: [],
        valueMetadata: [],
        warningMetadata: []
      },
      // 表单校验
      rules: {
        mcuChannel: [{required: true, message: "关联的MCU通道号不能为空", trigger: "blur"}],
        mcuTenantResourceId: [{required: true, message: "关联的MCU不能为空", trigger: "blur"}],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
        model: [{required: true, message: "关联的传感器不能为空", trigger: "blur"}]
      },
      mcuTenantResourceListData: [],
      sensorTenantTypeListData: [],
      tenantId: getTenantId(),
      formDisabled: false
    };
  },
  created() {
    this.getList();
    this.queryMcuTenantResourceListData();
  },
  methods: {
    /**  查询租户添加的MCU 列表  */
    queryMcuTenantResourceListData() {
      getMcuTenantResourceList({'tenantId': this.tenantId}).then(response => {
        this.mcuTenantResourceListData = response.data;
      });
    },
    /**  查询租户授权的MCU 列表  */
    querySensorTenantTypeListData() {
      let mcuModel = "";
      this.mcuTenantResourceListData.forEach(it => {
        if (it.id == this.form.mcuTenantResourceId) {
          mcuModel = it.model;
        }
      });
      getSensorTenantTypeInfoList({'tenantId': this.tenantId, 'mcuModel': mcuModel}).then(response => {
        this.sensorTenantTypeListData = response.data;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getSensorTenantResourcePage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        mcuTenantResourceId: undefined,
        mcuModel: undefined,
        mcuChannel: undefined,
        model: undefined,
        name: undefined,
        attributeMetadata: [],
        valueMetadata: [],
        warningMetadata: [],
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formDisabled = false;
      this.reset();
      this.open = true;
      this.title = "添加传感器配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row,handles) {
      console.log(handles)
      if (handles === 'info'){
      this.formDisabled = true;
      }else{
        this.formDisabled = false;
      }
      this.reset();
      const id = row.id;
      getSensorTenantResource(id).then(response => {
        this.form = response.data;
        this.form.attributeMetadata.forEach(it1=>{
          if (it1.htmlType === 'switch'){
            if (it1.inputValue==='true') {
              it1.inputValue=true
            }else if (it1.inputValue==='false'){
              it1.inputValue=false
            }else {
              it1.inputValue=true
            }
          }
        })
        this.open = true;
        this.title = "修改传感器配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        this.form.warningMetadata.forEach(it=>{
          this.form.valueMetadata.forEach(it1=>{
            if (it.code===it1.code){
              it.name=it1.name;
            }
          })
        })
        this.form.tenantId=this.tenantId
        // 修改的提交
        if (this.form.id != null) {
          updateSensorTenantResource(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSensorTenantResource(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除传感器配置编号为"' + id + '"的数据项?').then(function () {
        return deleteSensorTenantResource(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有传感器配置数据项?').then(() => {
        this.exportLoading = true;
        return exportSensorTenantResourceExcel(params);
      }).then(response => {
        this.$download.excel(response, '传感器租户配置.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    removeWarningMetadataItem(item) {
      let index = this.form.warningMetadata.indexOf(item)
      if (index !== -1) {
        this.form.warningMetadata.splice(index, 1)
      }
    },
    addWarningMetadataItem() {
      this.form.warningMetadata.push({ code: undefined, conditions: undefined, value: undefined});

    },
    changeSensorType(val) {
      this.sensorTenantTypeListData.forEach(it => {
        if (it.model === val) {
          this.form.name = it.name
          this.form.model = it.model
          this.form.mcuModel=it.mcuModel
          this.form.attributeMetadata=it.attributeMetadata
          this.form.valueMetadata=it.valueMetadata

          this.form.attributeMetadata.forEach(it1=>{
            if (it1.htmlType === 'switch'){
              if (it1.inputValue==='true') {
                it1.inputValue=true
              }else if (it1.inputValue==='false'){
                it1.inputValue=false
              }else {
                it1.inputValue=true
              }
            }
          })
        }
      })
    }
  }
};
</script>
